package dk.aau.walkietalkieui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.widget.Toast;
import dk.aau.walkietalkie.network.ConnectivityChecker;
import dk.aau.walkietalkieui.fragment.ChatFragment;
import dk.aau.walkietalkieui.fragment.ContactListFragment;
import dk.aau.walkietalkieui.fragment.ContactListFragment.IContactListFragment;

public class ContactListActivity extends Base_FragmentActivity implements
		IContactListFragment {

	private static final String SELECTED_NAME = "SelectedName";
	private static final String SELECTED_IP = "SelectedIp";

	private ChatFragment mChatFragment = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Toast.makeText(getApplicationContext(), R.string.welcome_toast,
		// Toast.LENGTH_LONG).show();
		// check connectivity on startup of main screen
		if (!ConnectivityChecker.isWifiEnabled(getApplicationContext())) {
			Toast.makeText(getApplicationContext(),
					R.string.activate_wifi_message,
					Toast.LENGTH_LONG).show();
		} else if (!ConnectivityChecker
				.isWifiConnected(getApplicationContext())) {
			Toast.makeText(getApplicationContext(),
					R.string.connect_wifi_message,
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onMenuItemSelected(int position) {
		String ip = ((ContactListFragment) getSupportFragmentManager()
				.findFragmentByTag(ContactListFragment.TAG)).getSelectedIp();
		String name = ((ContactListFragment) getSupportFragmentManager()
				.findFragmentByTag(ContactListFragment.TAG)).getSelectedName();

		switchToChatFragment(position, ip, name);
	}

	public ChatFragment getChatFragment() {
		return mChatFragment;
	}

	public void switchToChatFragment(int position, String ip, String name) {
		if (findViewById(R.id.ChatFragmentContent) != null) {
			// if the right panel exists, load the content
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.setCustomAnimations(R.anim.slide_in_top, R.anim.slide_out_right);
			mChatFragment = ChatFragment.newInstance(position, name, ip);
			ft.replace(R.id.ChatFragmentContent, mChatFragment,
					ChatFragment.TAG);

			// ft.addToBackStack(null);
			ft.commit();
		} else {
			Intent i = new Intent(this, ChatActivity.class);
			i.putExtra(ChatActivity.KEY_SELECTED_INDEX, position);
			i.putExtra(SELECTED_NAME, name);
			i.putExtra(SELECTED_IP, ip);
			startActivity(i);
		}
	}

}
